package com.blue.common.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blue.common.constants.AppConst;
import com.blue.common.utils.WebUtil;

/**
 * 设置公共参数 Filter
 * 1、BaseURL---->http://localhost:8080
 * 2、ctx---->request.contextPath
 * 3、currentURL---->当前地址
 * <p>User: 杨浩泉
 * <p>Date: 2015年9月14日
 * <p>Version: 1.0
 */

/**
 * 公共参数
 * 
 * @作者：杨浩泉
 * @时间：2016年11月9日
 * @版本： v1.0
 * 
 */
public class BaseFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		if (request.getAttribute(AppConst.CONTEXT_PATH) == null) {
			request.setAttribute(AppConst.CONTEXT_PATH, WebUtil.getContextPath(request));
		}
		if (request.getAttribute(AppConst.URI) == null) {
			request.setAttribute(AppConst.URI, WebUtil.getCurrentUri(request));
		}
		if (request.getAttribute(AppConst.URL) == null) {
			request.setAttribute(AppConst.URL, WebUtil.getCurrentUrl(request));
		}
		if (request.getAttribute(AppConst.URL) == null) {
			request.setAttribute(AppConst.URL, WebUtil.getCurrentUrl(request));
		}
		if (request.getAttribute(AppConst.SERVER_URL) == null) {
			request.setAttribute(AppConst.SERVER_URL, WebUtil.getServerUrl(request));
		}
		if (request.getAttribute(AppConst.PREREQUEST) == null) {
			request.setAttribute(AppConst.PREREQUEST, WebUtil.getBackURL(request));
		}

		if (request.getAttribute(AppConst.IP) == null) {
			request.setAttribute(AppConst.IP, WebUtil.getIpAddress(request));
		}

		chain.doFilter(request, response);
		return;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

}
